package com.coder.oj.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.coder.oj.common.core.BaseContext;
import com.coder.oj.common.exception.DataException;

import java.util.Date;

/**
 * jwt工具类
 * @author Bosen 2022/11/24 15:35
 **/
public class JwtUtil {
    /**
     * 过期时间
     */
    public static final long EXPIRE_TIME = 120 * 60 * 1000;

    /**
     * 密钥
     */
    private static final String SECRET = "coder-oj";

    /**
     * 生成签名
     * @author Bosen 2022/11/24 15:36
     **/
    public static String sign(long userId) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    .withAudience(String.valueOf(userId))
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception ignored) {
            return null;
        }
    }

    /**
     * 根据token获取userId
     * @author Bosen 2022/11/24 15:37
     **/
    public static Long getUserId(String token) {
        try {
            return Long.parseLong(JWT.decode(token).getAudience().get(0));
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 校验token 
     * @author Bosen 2022/11/24 15:36
     **/
    public static void checkSign(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            verifier.verify(token);
            // 缓存用户id
            BaseContext.setCurrentId(JwtUtil.getUserId(token));
        } catch (JWTVerificationException exception) {
            throw new DataException(401, "无效的token");
        }
    }
}
